package com.rw.base.http;

import com.blankj.utilcode.util.ToastUtils;
import com.rw.base.http.base.BaseResponse;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * @author: ZengZhenHua
 * @date: 2018/12/18
 * @email: cengzhenghua@163.com
 */
public class BaseObserver<T> implements Observer<BaseResponse<T>> {
    private HttpDataCallback<T> mSubscriberOnNextListener;
    private Disposable mDisposable;

    public BaseObserver(HttpDataCallback<T> onNextListener) {
        this.mSubscriberOnNextListener = onNextListener;
    }

    @Override
    public void onSubscribe(Disposable d) {
        this.mDisposable = d;
    }

    @Override
    public void onNext(BaseResponse<T> tBaseResponse) {
        if (mSubscriberOnNextListener != null) {
            if (tBaseResponse.isSuccess()) {
                mSubscriberOnNextListener.onNext(tBaseResponse.data);
            } else {
                mSubscriberOnNextListener.onError(tBaseResponse.message);
            }
        }
    }


    @Override
    public void onError(Throwable e) {
        if (e instanceof SocketTimeoutException) {
            ToastUtils.showShort("请求超时");
        } else if (e instanceof ConnectException) {
            ToastUtils.showShort("网络中断，请检查您的网络状态");
        } else {
            ToastUtils.showShort(e.getMessage());
        }
    }

    @Override
    public void onComplete() {

    }

    public void cancelRequest() {
        if (mDisposable != null && mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }
}
